package com.leo.springbootmultithreadbasic.threadcounter.countdownlatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * @author Leo
 * @version V1.0
 */
public class MainDemo {

    private static Logger logger = LoggerFactory.getLogger(MainDemo.class);

    // 线程数量
    private static final int THREAD_COUNT_NUM = 5;

    // 创建CountDownLatch实例
    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(THREAD_COUNT_NUM);


    public static void main(String[] args) {
        test();
    }

    /**
     * 测试场景：
     *
     * N个子线程完成各自的任务后，开始执行主线程。
     */
    private static void test() {
        for (int i = 0; i <  THREAD_COUNT_NUM; i++) {
            int index = i + 1;

            // 创建线程
            new Thread(() -> {
                logger.info("第{}子线程", index);
                // 每个线程执行完毕后，计数器减1
                COUNT_DOWN_LATCH.countDown();
            }).start();
        }

        // 等待检查，上述全部子线程执行完毕后，才会执行await()方法之后的代码
        try {
            COUNT_DOWN_LATCH.await();
            logger.info("所有的子线程已经执行完毕，开始执行主线程！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
